﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Services.StartServices;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    // 服务类实现
    public class HistoryRecordService:IHistoryRecordService
    {
        /// <summary>
        /// 服务接口
        /// </summary>
        private readonly IHistoryRecordRepository _historyRecordRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<HistoryRecordService> _logger;

        /// <summary>
        /// 上下文
        /// </summary>
        private readonly AgricultureDbContext _db;
         
        /// 对象关系映射
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="historyRecordRepository">服务接口</param>

        public HistoryRecordService(IHistoryRecordRepository historyRecordRepository, AgricultureDbContext db, IMapper mapper, ILogger<HistoryRecordService> logger)
        {
            _historyRecordRepository = historyRecordRepository;
            _db=db;
            _mapper=mapper;
            _logger = logger;

        }

        /// <summary>
        /// 历史记录显示
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns><返回数据/returns>
        public async Task<PageOutput<HistoryOutPut>> GetHistoryRecordsAsync(HistoryInput? input)
        {
            // 可以在此处添加业务逻辑，如权限检查、数据验证等

            // 调用仓储接口获取种母历史记录
            var history= await _historyRecordRepository.GetHistoryRecordsAsync();
           

            // 应用额外的筛选条件
            if (!string.IsNullOrEmpty(input.EarTag))
            {
                history = history.Where(c => c.EarTag.Contains(input.EarTag)).ToList();
            }
            if (!string.IsNullOrEmpty(input.Sdate))
            {
                var startDate = DateTime.Parse(input.Sdate);
                history = history.Where(c => c.BreedDate >= startDate).ToList();
            }
            if (!string.IsNullOrEmpty(input.Edate))
            {
                var endDate = DateTime.Parse(input.Edate).AddDays(1);
                history = history.Where(c => c.BreedDate < endDate).ToList();
            }

            // 分页处理
            var pagedData = history.OrderBy(c => c.Hrid)
                                        .Skip((input.PageIndex - 1) * input.PageSize)
                                        .Take(input.PageSize)
                                        .ToList();

            var result = new PageOutput<HistoryOutPut>
            {
                TotalCount = history.Count(), // 计算筛选后的总条数
                PageSize = input.PageSize,
                Data = _mapper.Map<List<HistoryOutPut>>(pagedData)
            };

            return result;

        }





        /// <summary>
        /// 逻辑删除历史记录数据
        /// </summary>
        /// <param name="hrid">主键id</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> DeleteHistoryrecord(int hrid)
        {
            return await _historyRecordRepository.DeleteHistoryrecord(hrid);
        }


        /// <summary>
        /// 批量逻辑历史记录表
        /// </summary>
        /// <param name="hrids">id</param>
        /// <returns>返回数据</returns>
        public async Task<int> DeleteRangeHistoryrecord(IEnumerable<int> hrids)
        {
            return await _historyRecordRepository.DeleteRangeHistoryrecord(hrids);
        }




        /// <summary>
        /// 添加种母历史记录数据
        /// </summary>
        /// <param name="inputs">实体</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<int> AddHistoryrecordAsync(List<Historyrecord> inputs)
        {
            // 为每个输入项设置创建相关的属性
            foreach (var input in inputs)
            {
                input.CreateTime = DateTime.Now;
                input.CreateName = "Admin";
                input.UpdateTime = DateTime.Now;
                input.UpdateName = "张三";
                input.Isdel = false;
            }
            // 批量添加期初表数据
            await _historyRecordRepository.AddHistoryrecordAsync(inputs);
            return inputs.Count;
        }


        /// <summary>
        /// 反填种母历史记录表
        /// </summary>
        /// <param name="earTag">根据耳号反填</param>
        /// <returns>返回数据</returns>
        public async Task<HistoryOutPut> GetHistoryByIdAsync(string? earTag)
        {
            var history = await _historyRecordRepository.GetHistoryRecordsAsync();
            var historylist = (from historys in history
                               join breedinginfo in _db.Breedinginfos
                               on historys.EarTag equals breedinginfo.EarTag
                               join sheepPregnancy in _db.Sheeppregnancies
                               on historys.EarTag equals sheepPregnancy.EarTag
                               join childbirth in _db.Childbirths
                               on historys.EarTag equals childbirth.EarTag
                               join sheepablactation in _db.Sheepablactations
                               on historys.EarTag equals sheepablactation.EarTag
                               where historys.EarTag==earTag
                               select new HistoryOutPut()
                               {
                                   Hrid = historys.Hrid,
                                   EarTag = breedinginfo.EarTag,
                                   BreedDate = breedinginfo.BreedDate,
                                   BreedingRaw = breedinginfo.FirstMatingRam,
                                   PregnancyDate = sheepPregnancy.PregnancyDate,
                                   PregnancyResult = sheepPregnancy.PregnancyResult,
                                   DeliveryDate = childbirth.ChildbirthDate,
                                   HealthyNumber = childbirth.HealthyNumber,
                                   HealthyTotalWeight = historys.HealthyTotalWeight,
                                   LambNumber = childbirth.LambNumber,
                                   MalformationNumber = childbirth.MalformationNumber,
                                   StillbirthNumber = childbirth.StillbirthNumber,
                                   MummyNumber = childbirth.MummyNumber,
                                   FreaksNumber = childbirth.FreaksNumber,
                                   WeaningDate = sheepablactation.Ablactation,
                                   WeaningCount = sheepablactation.AblactationNum,
                                   WeaningWeight = sheepablactation.AblactationWeight,
                                   CurrentPregnancy = historys.CurrentPregnancy,
                                   CreateName = historys.CreateName,
                                   CreateTime = historys.CreateTime,
                                   UpdateName = historys.UpdateName,
                                   UpdateTime = historys.UpdateTime,
                                   Isdel = historys.Isdel,
                               }).FirstOrDefault();
            return _mapper.Map<HistoryOutPut>(historylist);
        }




        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="history">期初实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> UpdateAsync(Historyrecord history)
        {
            var list = _mapper.Map<Historyrecord>(history);
            return await _historyRecordRepository.UpdateHisRecordAsync(list);
        }













    }
}
